﻿using System.Collections.ObjectModel;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using SimpleTool.Base;
using SimpleTool.Server;

namespace SimpleTool.ActivityUnit
{
    public delegate void MessageProPlant(FlyingDove Message);

    [Flags]
    public enum MessageProPlantType
    {
        Message = 1,
        Question = 2,
        Success = 4,
        Failed = 8,
        PushFinish = 16,
        HeartBeats = 32,
        Initialize = 128,
        DimProcess = 256,
        ResultRegister = 512
    }

    public enum DemandType
    {
        Invalid,
        Mes
    }

    //  消息通知确认
    public sealed class FlyingDove
    {
        public MessageProPlantType Type { set; get; }

        public object? Message { set; get; }

        public bool AssertQuestion { set; get; }

        public int Row { set; get; }

        public FlyingDove(MessageProPlantType type, object? message, int row, bool assertQuestion = false)
        {
            Type = type;
            Message = message;
            Row = row;
            AssertQuestion = assertQuestion;
        }

        public FlyingDove(MessageProPlantType type, object? message)
        {
            Type = type;
            Message = message;
        }
    }

    public sealed class TestItemSurfaceSealed
    {
        public string ActivityName { set; get; } = string.Empty;

        public Brush ItemBack { set; get; } = Brushes.Transparent;

        public TestItemSurfaceSealed(string activityName, string itemBack)
        {
            ActivityName = activityName;
            object? brushObject = new BrushConverter().ConvertFrom(itemBack);
            if (brushObject != null) ItemBack = (Brush)brushObject;
        }

        public TestItemSurfaceSealed(string activityName, Brush itemBack)
        {
            ActivityName = activityName;
            if (itemBack != null) ItemBack = itemBack;
        }

        public TestItemSurfaceSealed(string activityName, Color itemBack)
        {
            ActivityName = activityName;
            ItemBack = new SolidColorBrush(itemBack);
        }
    }

    public sealed class KeyValuePairSealed : Notify
    {
        private Visibility VisibilityStdin = Visibility.Collapsed;

        public string Icon { set; get; }

        public string Name { set; get; }

        public Brush ForeGround { set; get; }

        public Visibility Visibility 
        {
            set
            {
                VisibilityStdin = value;
                propertyChangeSend(nameof(Visibility));
            }
            get
            {
                return VisibilityStdin;
            }
        
        }

        public KeyValuePairSealed(string icon, string name, Brush? foreGround = null)
        {
            this.Icon = icon;
            this.Name = name;
            if (foreGround is null)
            {
                ForeGround = "DeepMatrix".FindSolidBrush();
            }
            else
            {
                ForeGround = foreGround;
            }
        }
    }

    public sealed class TestItemDeepSeatedSealed
    {
        public bool Status = true;

        public int Priority = 0;

        public string Step;

        public string Command;

        public string PassFlag;

        public string ErrorFlag;

        public string? PassMatch;

        public string? PassValueVirify;

        public int? SendDelayMs;

        public int? TimeoutMs;

        public int? MaxRetryCount;

        public int? MaxContentLength;

        public int? RetryDelayMs;

        public bool? IsLinkedToPrevious;

        public bool? IsCombination;

        public bool? IsBluetoothBoard;

        public bool? IsHandDownValue;

        public string? BluethAccording;

        public string? AddtionAccording;

        public bool? IsXorVerify;

        public bool? AllowableEntry;

        public string? AllowableString;

        public string? AllowableEntryType;

        public string? ValidValueRange;

        public string? ValueProcessingType;

        public string? WriteDBdataUseTraces;

        public string? AppendType;

        public string? AppendValue;

        public string? ContainAtthis;

        public bool? IsAccessOneNet;

        public string? OneNetUrl;

        public string? OneNetProductID;

        public TestItemDeepSeatedSealed(string step, string command, string passFlag, string errorFlag)
        {
            Step = step;
            Command = command;
            PassFlag = passFlag;
            ErrorFlag = errorFlag;
        }

        public TestItemDeepSeatedSealed(string step)
        {
            Step = step;
            Command = string.Empty;
            PassFlag = string.Empty;
            ErrorFlag = string.Empty;
        }

        public TestItemDeepSeatedSealed()
        {
            Step = string.Empty;
            Command = string.Empty;
            PassFlag = string.Empty;
            ErrorFlag = string.Empty;
        }
    }

    public sealed class WorkOrderFieldMapSealed
    {
        //  主键ID
        public string? Id { get; set; }

        //  序列号
        public string? Sn { get; set; }

        //  IMEI码
        public string? Imei { get; set; }

        //  Secret密钥
        public string? SecretKey { get; set; }

        //  OneNet产品ID
        public string? OnenetProductId { get; set; }

        //  OneNet注册ID
        public string? OnenetRegisterId { get; set; }

        //  产品API密钥
        public string? ProductApiKey { get; set; }

        //  设备API密钥
        public string? DeviceApiKey { get; set; }

        //  OneNet验证信息
        public string? OnenetVerifyInfo { get; set; }

        //  蓝牙MAC地址
        public string? BlueMac { get; set; }

        //  状态
        public string? State { get; set; }

        //  产品名称
        public string? ProductName { get; set; }

        //  产品类型
        public string? ProductType { get; set; }

        //  产品编号
        public string? ProductNum { get; set; }

        //  产品版本
        public string? ProductVersion { get; set; }

        //  工单编号
        public string? WorkorderNum { get; set; }

        //  SIM卡号
        public string? Sim { get; set; }

        //  版本号
        public string? Version { get; set; }

        public WorkOrderFieldMapSealed() { }

    }

    public sealed class ActivityAssistBehivor
    {
        public static readonly ActivityAssistBehivor Behivor = new();

        public string AttributeConfigProductType = string.Empty;

        public readonly List<string> fieldHideds = [];

        public readonly List<string> LongTimeTak = ["prod AT+TEST=NFC_TEST"];

        public readonly Dictionary<string, bool> AttributePrimaryMap = new ()
        {
            [nameof(TestItemDeepSeatedSealed.Status)] = true,
            [nameof(TestItemDeepSeatedSealed.Priority)] = true,
            [nameof(TestItemDeepSeatedSealed.Step)] = true,
            [nameof(TestItemDeepSeatedSealed.Command)] = true,
            [nameof(TestItemDeepSeatedSealed.PassFlag)] = true,
            [nameof(TestItemDeepSeatedSealed.ErrorFlag)] = true
        };

        public readonly Dictionary<ProductFlag, string> ProductFlagChzMap = new() 
        { 
            { ProductFlag.HYC, "和易充" }, 
            { ProductFlag.ZNMS, "门锁" } 
        };

        public readonly List<string> AttributeCanCheckMap =
        [
            nameof(TestItemDeepSeatedSealed.PassFlag),
            nameof(TestItemDeepSeatedSealed.PassMatch),
            nameof(TestItemDeepSeatedSealed.PassValueVirify),
            nameof(TestItemDeepSeatedSealed.MaxContentLength),
            nameof(TestItemDeepSeatedSealed.IsLinkedToPrevious),
            nameof(TestItemDeepSeatedSealed.ValidValueRange),
            nameof(TestItemDeepSeatedSealed.AppendValue),
            nameof(TestItemDeepSeatedSealed.ContainAtthis),
            nameof(TestItemDeepSeatedSealed.WriteDBdataUseTraces),
            nameof(TestItemDeepSeatedSealed.IsAccessOneNet)
        ];

        public readonly Dictionary<string, KeyValuePair<string, DependencyDBPropertyType>> DBDependencyMap = new ()
        {
            [nameof(WorkOrderUnfold.SnSuffix)] = new KeyValuePair<string, DependencyDBPropertyType>("Sn", DependencyDBPropertyType.Difference),
            [nameof(WorkOrderPreview.SnStart)] = new KeyValuePair<string, DependencyDBPropertyType>("Sn", DependencyDBPropertyType.PointStart),
            [nameof(WorkOrderPreview.SnEnd)] = new KeyValuePair<string, DependencyDBPropertyType>("Sn", DependencyDBPropertyType.PointEnd),
            [nameof(WorkOrderUnfold.ImeiSuffix)] = new KeyValuePair<string, DependencyDBPropertyType>("Imei", DependencyDBPropertyType.Difference),
            [nameof(WorkOrderPreview.ImeiStart)] = new KeyValuePair<string, DependencyDBPropertyType>("Imei", DependencyDBPropertyType.PointStart),
            [nameof(WorkOrderPreview.ImeiEnd)] = new KeyValuePair<string, DependencyDBPropertyType>("Imei", DependencyDBPropertyType.PointEnd)
        };

        public readonly Dictionary<string, string> DBReserveDutyTranslationMap = new ()
        {
            [nameof(WorkOrderUnfold.Id)] = "主键ID",
            [nameof(WorkOrderUnfold.Sn)] = "序列号",
            [nameof(WorkOrderUnfold.Imei)] = "IMEI码",
            [nameof(WorkOrderUnfold.SecretKey)] = "Secret密钥",
            [nameof(WorkOrderUnfold.OnenetProductId)] = "OneNet产品ID",
            [nameof(WorkOrderUnfold.OnenetRegisterId)] = "OneNet注册ID",
            [nameof(WorkOrderUnfold.DeviceApiKey)] = "产品API密钥",
            [nameof(WorkOrderUnfold.ProductApiKey)] = "设备API密钥",
            [nameof(WorkOrderUnfold.BlueMac)] = "蓝牙MAC地址",
            [nameof(WorkOrderUnfold.State)] = "状态",
            [nameof(WorkOrderUnfold.ProductName)] = "产品名称",
            [nameof(WorkOrderUnfold.ProductType)] = "产品类型",
            [nameof(WorkOrderUnfold.ProductNum)] = "产品编号",
            [nameof(WorkOrderUnfold.ProductVersion)] = "产品版本",
            [nameof(WorkOrderUnfold.WorkorderNum)] = "工单编号"
        };

        public readonly Dictionary<string, string> DBPreviewTranslationMap = new ()
        {
            [nameof(WorkOrderUnfold.UsingTime)] = "写",
            [nameof(WorkOrderUnfold.VerifyTime)] = "读",
            [nameof(WorkOrderUnfold.SnSuffix)] = "SN后缀",
            [nameof(WorkOrderUnfold.ImeiSuffix)] = "IMEI后缀"
        };

        public readonly Dictionary<string, (string, int)> ParamReserveDutyMap = new ()
        {
            ["ORDER"] = ("工单", 1),
            ["IMEI"] = ("IMEI", 2),
            ["SN"] = ("SN", 3),
            ["BLUE"] = ("蓝牙", 4),
            ["DOID"] = ("DOID", 5),
            ["QRCODE_1"] = ("二维码1", 6),
            ["QRCODE_2"] = ("二维码2", 7)
        };

        public readonly Dictionary<string, string> AttributeTranslationMap = new ()
        {
            [nameof(TestItemDeepSeatedSealed.Status)] = "状态",
            [nameof(TestItemDeepSeatedSealed.Priority)] = "优先级",
            [nameof(TestItemDeepSeatedSealed.Step)] = "步骤",
            [nameof(TestItemDeepSeatedSealed.Command)] = "指令",
            [nameof(TestItemDeepSeatedSealed.PassFlag)] = "通过标识",
            [nameof(TestItemDeepSeatedSealed.ErrorFlag)] = "异常标识",
            [nameof(TestItemDeepSeatedSealed.PassMatch)] = "通过值匹配",
            [nameof(TestItemDeepSeatedSealed.PassValueVirify)] = "通过值校验",
            [nameof(TestItemDeepSeatedSealed.SendDelayMs)] = "延迟(ms)",
            [nameof(TestItemDeepSeatedSealed.MaxRetryCount)] = "重试次数",
            [nameof(TestItemDeepSeatedSealed.MaxContentLength)] = "字符长度校验",
            [nameof(TestItemDeepSeatedSealed.TimeoutMs)] = "测试项超时(ms)",
            [nameof(TestItemDeepSeatedSealed.RetryDelayMs)] = "重试延迟(ms)",
            [nameof(TestItemDeepSeatedSealed.IsLinkedToPrevious)] = "关联上个输出",
            [nameof(TestItemDeepSeatedSealed.IsHandDownValue)] = "继承值",
            [nameof(TestItemDeepSeatedSealed.ValidValueRange)] = "数据有效区间",
            [nameof(TestItemDeepSeatedSealed.ValueProcessingType)] = "数据处理类型",
            [nameof(TestItemDeepSeatedSealed.WriteDBdataUseTraces)] = "数据使用痕迹",
            [nameof(TestItemDeepSeatedSealed.AppendType)] = "追加类型",
            [nameof(TestItemDeepSeatedSealed.AppendValue)] = "追加数据",
            [nameof(TestItemDeepSeatedSealed.IsCombination)] = "拼接指令",
            [nameof(TestItemDeepSeatedSealed.BluethAccording)] = "蓝牙地址中间字符",
            [nameof(TestItemDeepSeatedSealed.AddtionAccording)] = "拼接中间字符",
            [nameof(TestItemDeepSeatedSealed.IsBluetoothBoard)] = "连接蓝牙板串口",
            [nameof(TestItemDeepSeatedSealed.IsXorVerify)] = "位异或校验",
            [nameof(TestItemDeepSeatedSealed.ContainAtthis)] = "包含",
            [nameof(TestItemDeepSeatedSealed.AllowableEntry)] = "数据准入校验",
            [nameof(TestItemDeepSeatedSealed.AllowableString)] = "过滤字符",
            [nameof(TestItemDeepSeatedSealed.AllowableEntryType)] = "数据准入类型",
            [nameof(TestItemDeepSeatedSealed.IsAccessOneNet)] = "OneNet平台状态检查",
            [nameof(TestItemDeepSeatedSealed.OneNetUrl)] = "OneNet地址",
            [nameof(TestItemDeepSeatedSealed.OneNetProductID)] = "OneNet产品ID"
        };

        public readonly Dictionary<string, (string, bool)> MesTranslationMap = new ()
        {
            [nameof(MesResportServer.MesargGroups.Barcodes)] = ("主板二维码", true),
            [nameof(MesResportServer.MesargGroups.WorkOrder)] = ("工单", true),
            [nameof(MesResportServer.MesargGroups.StationName)] = ("工位", true),
            [nameof(MesResportServer.MesargGroups.WorkProcedure)] = ("工序", true),
            [nameof(MesResportServer.MesargGroups.UserAccount)] = ("操作员", true),
            [nameof(MesResportServer.MesargGroups.BindingInfo)] = ("绑定信息", false),
            [nameof(MesResportServer.MesargGroups.TestInfo)] = ("测试结果", false),
            [nameof(MesResportServer.MesargGroups.NGCode)] = ("不良测试说明", false),
            ["AccessUrl"] = ("URL", true)
        };

        public readonly Dictionary<string, List<string>> AttributeExpectsMap = new ()
        {
            //  状态
            [nameof(TestItemDeepSeatedSealed.Status)] = ["False", "True"],

            //  优先级
            [nameof(TestItemDeepSeatedSealed.Priority)] = [.. Enumerable.Range(1, 25).Select(x => x.GetSafetyChar())],

            //  步骤 - 智能门锁
            [$"{nameof(TestItemDeepSeatedSealed.Step)}-{ProductFlag.ZNMS}"] =
            [
                //  单板
                "进入工厂测试模式",
                "验证IMEI测试",
                "读取版本号",
                "加密芯片验证",
                "flash读取",
                "电量测试",
                "复位测试",
                "触摸按键测试",
                "nfc卡录入测试",
                "nfc卡验证测试",
                "指纹自检测",
                "指纹验证测试",
                "低功耗测试",
                "CAT1测试",

                //  鸿蒙锁_待机电流 - 写号校号测试_中移
                "1001#输入提示",
                "进入待机电流测试",
                "写SN",
                "写DOID",
                "写IMEI",
                "写BLE_MAC",
                "校号测试（读SN）",
                "校号测试（读DOID）",
                "校号测试（读IMEI）",
                "校号测试（读BLE_MAC）",
                "读产品信息测试",

                //  鸿蒙锁_信号测试_高远
                "检查sim卡",
                "检查网络注册",
                "读取信号强度",

                //  鸿蒙锁_蓝牙测试_中移
                "蓝牙功能测试",

                //  鸿蒙锁_包装号段校验_中移
                "验证SN,IMEI测试",

                //  鸿蒙锁_OQC检测_中移
                "获取待机电流测试结果",
                "验证SN测试",
                "验证IMEI测试",
            ],

            //  步骤 - 和易充
            [$"{nameof(TestItemDeepSeatedSealed.Step)}-{ProductFlag.HYC}"] =
            [
                //  从和易充_整机测试1_中移提取数据
                "进入测试模式",
                "读取单板测试标志",
                "临时蓝牙MAC写入",
                "喇叭测试",
                "网络指示灯测试",
                "第一次刷卡测试",
                "温度传感器测试",
                "功率测试参数写入",

                //  从和易充_整机测试2_中移提取数据
                "网络指示灯测试",
                "触摸按键测试",
                "充电指示灯测试",
                "读取信号强度",
                "SIM卡测试",
                "OneNet平台设备状态查询",

                //  从和易充_写号校号_中移提取数据
                "写SN",
                "写IMEI",
                "写BLE_MAC",
                "校号测试（读SN）",
                "校号测试（读IMEI）",
                "校号测试（读BLE_MAC）"
            ],

            //  指令 - 智能门锁
            [$"{nameof(TestItemDeepSeatedSealed.Command)}-{ProductFlag.ZNMS}"] =
            [
                //  单板测试
                "AT+START",
                "AT+DEVINFO",
                "AT+READVER",
                "AT+ENICTEST",
                "AT+FLASHTEST",
                "AT+VOLTAGE=58%",
                "AT+MOTOR",
                "AT+FACE_TEST",
                "AT+RESET",
                "AT+KEYBOARD",
                "AT+IC_REGIST",
                "AT+IC_VERIFY",
                "AT+FP_REGIST",
                "AT+FP_VERIFY",
                "AT+ANTI",
                "AT+LOW_VOLTAGE",
                "AT+NBTEST=",
                "AT+END",

                //  鸿蒙锁_待机电流 - 写号校号测试_中移
                "AT+STDCURSTART",
                "AT+TEST=SET_SN",
                "AT+TEST=SET_DOID",
                "AT+TEST=SET_IMEI",
                "AT+TEST=SET_BLE_MAC",
                "AT+TEST=READ_SN",
                "AT+TEST=READ_DOID",
                "AT+TEST=READ_IMEI",
                "AT+TEST=READ_BLE_MAC",
                "AT+TEST=SET_ONENET_PRODUCT_ID",
                "AT+TEST=SET_ONENET_ACCESS_KEY",
                "AT+TEST=SET_IOT_PRODUCT_ID",
                "AT+TEST=SET_IOT_ACCESS_KEY",
                "AT+TEST=READ_ONENET_PRODUCT_ID",
                "AT+TEST=READ_ONENET_ACCESS_KEY",
                "AT+TEST=READ_IOT_PRODUCT_ID",
                "AT+TEST=READ_IOT_ACCESS_KEY",

                //  鸿蒙锁_信号测试_高远
                "AT+CIMI",
                "AT+COPS?",
                "AT+CSQ",

                //  鸿蒙锁_蓝牙测试_中移
                "AT+SCANADD",

                //  鸿蒙锁_包装号段校验_中移
                "START",

                //  鸿蒙锁_OQC检测_中移
                "AT+QCSTDCURFLAG",
                "AT+QCREAD_SN",
                "AT+QCREAD_IMEI",
            ],

            //  指令 - 和易充
            [$"{nameof(TestItemDeepSeatedSealed.Command)}-{ProductFlag.HYC}"] =
            [
                //  从和易充_整机测试
                "prod AT+TEST=TEST_MODE",
                "prod AT+TEST=READ_FLAG",
                "prod AT+TEST=VOICE_TEST",
                "prod AT+TEST=NFC_TEST",
                "prod AT+TEST=SIM_TEST",
                "prod AT+TEST=TEMP_VALUE",
                "prod AT+TEST=SET_PW_PARAMS,5,21,43",
                "prod AT+TEST=NET_LED",
                "prod AT+TEST=TOUCH_TEST",
                "prod AT+TEST=OUTLET_LED",
                "prod AT+TEST=CSQ",

                //  从和易充_写号校号_中移提取数据
                "prod AT+TEST=SET_SN",
                "prod AT+TEST=SET_IMEI,",
                "prod AT+TEST=SET_MAC,",
                "prod AT+TEST=GET_SN",
                "prod AT+TEST=GET_IMEI",
                "prod AT+TEST=GET_MAC",
                "prod AT+TEST=SET_FLAG"
            ],

            //  通过标识
            [nameof(TestItemDeepSeatedSealed.PassFlag)] = ["OK", "SCAN_OK", "Card_ID", "FLAG", "READ IMSI", "READ CSQ"],

            //  异常标识
            [nameof(TestItemDeepSeatedSealed.ErrorFlag)] = ["NG", "SCAN_TIME_OUT", "SCAN_NG"],

            //  通过值匹配
            [nameof(TestItemDeepSeatedSealed.PassMatch)] =
            [
                "(?-i)Card_ID\\W*((:?[^\\W]+\\s+){3}[^\\W]{2})",
                "(?-i)FLAG\\W*([^\\W]+)",
                "(?-i)TEMP\\W*([\\d]+)",
                "(?-i)(([0-9]+[\\.*])+[0-9]*)",
                "(?-i)SE-ACCBC10-B00\\W*(.+)[^\\s\\n\\r]*",
                "(?-i)SE-CPBDL00-B00\\W*(.+)[^\\s\\n\\r]*",
                "(?-i)CSQ\\W*(([^\\W]+[^\\s]*)+)",
                "(?-i)IMSI\\W*(([^\\W]+[^\\s]*)+)",
                "(?-i)UID\\s*=\\s*\\W*([0-9a-zA-Z]+)\\W*"
            ],

            //  延迟(ms)
            [nameof(TestItemDeepSeatedSealed.SendDelayMs)] = [.. Enumerable.Range(1, 25).Select(x => x.GetSafetyChar() + "000")],

            //  重试次数
            [nameof(TestItemDeepSeatedSealed.MaxRetryCount)] = [.. Enumerable.Range(1, 10).Select(x => x.GetSafetyChar())],

            //  字符长度校验
            [nameof(TestItemDeepSeatedSealed.MaxContentLength)] = [.. Enumerable.Range(1, 50).Select(x => x.GetSafetyChar())],

            //  测试项超时(ms)
            [nameof(TestItemDeepSeatedSealed.TimeoutMs)] = [.. Enumerable.Range(1, 25).Select(x => x.GetSafetyChar() + "000")],

            //  重试延迟(ms)
            [nameof(TestItemDeepSeatedSealed.RetryDelayMs)] = [.. Enumerable.Range(1, 25).Select(x => x.GetSafetyChar() + "000")],

            //  关联上个输出
            [nameof(TestItemDeepSeatedSealed.IsLinkedToPrevious)] = ["False", "True"],

            //  拼接指令
            [nameof(TestItemDeepSeatedSealed.IsCombination)] = ["False", "True"],

            //  蓝牙地址中间字符
            [nameof(TestItemDeepSeatedSealed.BluethAccording)] = ["-", ":"],

            //  拼接中间字符
            [nameof(TestItemDeepSeatedSealed.AddtionAccording)] = [",", ":", "="],

            //  位异或校验
            [nameof(TestItemDeepSeatedSealed.IsXorVerify)] = ["False", "True"],

            //  连接蓝牙板串口
            [nameof(TestItemDeepSeatedSealed.IsBluetoothBoard)] = ["False", "True"],

            //  数据准入校验
            [nameof(TestItemDeepSeatedSealed.AllowableEntry)] = ["False", "True"],

            //  继承值
            [nameof(TestItemDeepSeatedSealed.IsHandDownValue)] = ["False", "True"],

            //  包含
            [nameof(TestItemDeepSeatedSealed.ContainAtthis)] = ["IMEI", "SN", "QRCODE", "DOID", "BLUE", "产品ID", "产品密钥", "产品自有ID", "产品自有密钥"],

            //  数据准入类型
            [nameof(TestItemDeepSeatedSealed.AllowableEntryType)] = ["HINT", "DB", "IMEI", "SN", "DOID", "BLUE"],

            //  数据使用痕迹
            [nameof(TestItemDeepSeatedSealed.WriteDBdataUseTraces)] = ["写", "读"],

            //  数据有效区间
            [nameof(TestItemDeepSeatedSealed.ValidValueRange)] = ["6,31", "10,50", "0,60"],

            //  数据处理类型
            [nameof(TestItemDeepSeatedSealed.ValueProcessingType)] = ["左值", "右值", "整值", "蓝牙", "标识"],

            //  追加类型
            [nameof(TestItemDeepSeatedSealed.AppendType)] = ["蓝牙", "序列号", "IMEI号", "产品ID", "产品密钥", "产品自有ID", "产品自有密钥"],

            //  追加数据
            [nameof(TestItemDeepSeatedSealed.AppendValue)] = ["实时蓝牙扫描", "数据库", "随机(蓝牙)", "r6975tQ0t1", "i+Op9YvTx/+xpQ1fh991C3+BBQ+PGz0laZ9rxes7O9c="],

            //  OneNet平台状态检查
            [nameof(TestItemDeepSeatedSealed.IsAccessOneNet)] = ["False", "True"],

            //  OneNet地址
            [nameof(TestItemDeepSeatedSealed.OneNetUrl)] = ["https://  iot-api.heclouds.com/device/detail"],

            //  OneNet产品ID
            [nameof(TestItemDeepSeatedSealed.OneNetProductID)] = ["8lx67TtYDs"]
        };

        public readonly Dictionary<string, (string, int)> TestFlagsMap = new ()
        {
            [$"{ProductFlag.HYC}-00"] = ("烧录初始状态", 0),
            [$"{ProductFlag.HYC}-81"] = ("整机测试1", 1),
            [$"{ProductFlag.HYC}-03"] = ("老化测试", 2),
            [$"{ProductFlag.HYC}-83"] = ("老化测试", 3),
            [$"{ProductFlag.HYC}-93"] = ("功率检测", 4),
            [$"{ProductFlag.HYC}-97"] = ("写号校号", 5),
            [$"{ProductFlag.HYC}-9f"] = ("整机测试2", 6)
        };        //  和易充标识

        public readonly Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> ProductFixedOpptions = new ()
        {
            {
                new("\ue615", "产品管理", "BurgundyNight".FindSolidBrush())
                {
                    Visibility = Visibility.Visible
                },
                [
                    new("\ue615", "产品添加", "BurgundyNight".FindSolidBrush()),
                    new("\ue62a", "产品预览", "BurgundyNight".FindSolidBrush())
                ]
            },
            {
                new("\ue616", "预置数据库", "BurgundyNight".FindSolidBrush())
                {
                    Visibility = Visibility.Visible
                },
                [
                    new("\ue602", "工单添加", "BurgundyNight".FindSolidBrush()),
                    new("\ue631", "工单预览", "BurgundyNight".FindSolidBrush()),
                    new("\ue68e", "字段映射", "BurgundyNight".FindSolidBrush())
                ]
            }
        };
    
        public readonly Dictionary<KeyValuePairSealed, ObservableCollection<KeyValuePairSealed>> ConfigFixedOpptions = new ()
        {
            {
                new KeyValuePairSealed("\ue60c", "添加步骤")
                {
                    Visibility = Visibility.Visible
                },
                [
                    new KeyValuePairSealed("\ue615", "常规步骤", "BurgundyNight".FindSolidBrush()),
                    new KeyValuePairSealed("\ue615", "值校验步骤", "BurgundyNight".FindSolidBrush()),
                    new KeyValuePairSealed("\ue615", "扫描蓝牙步骤", "BurgundyNight".FindSolidBrush()),
                    new KeyValuePairSealed("\ue615", "写入蓝牙步骤", "BurgundyNight".FindSolidBrush()),
                    new KeyValuePairSealed("\ue615", "首次刷卡步骤", "BurgundyNight".FindSolidBrush()),
                    new KeyValuePairSealed("\ue615", "验证刷卡步骤", "BurgundyNight".FindSolidBrush())
                ]
            },
            {
                new KeyValuePairSealed("\ue623", "编辑配置"),
                []
            },
            {
                new KeyValuePairSealed("\ue782", "保存配置"),
                []
            },
            {
                new KeyValuePairSealed("\ue645", "导入配置")
                {
                    Visibility = Visibility.Visible
                },
                []
            },
            {
                new KeyValuePairSealed("\ue643", "导出配置"),
                []
            },
            {
                new KeyValuePairSealed("\ue6bd", "回滚配置"),
                []
            },
            {
                new KeyValuePairSealed("\ue608", "退出配置"),
                []
            }
        };

        public readonly Dictionary<string, TestItemDeepSeatedSealed> FixedAtrributeTemplates = new()
        {
            ["常规步骤"] = new TestItemDeepSeatedSealed()
            {
                Status = true,
                Priority = 0,
                PassFlag = "OK",
                ErrorFlag = "NG"
            },
            ["值校验步骤"] = new TestItemDeepSeatedSealed()
            {
                Status = true,
                Priority = 0,
                Step = "温度传感器测试",
                Command = "prod AT+TEST=TEMP_VALUE",
                PassFlag = "OK",
                ErrorFlag = "NG",
                PassMatch = "(?-i)TEMP\\W*([\\d]+)",
                ValidValueRange = "10, 50",
                ValueProcessingType = "整值"
            },
            ["扫描蓝牙步骤"] = new TestItemDeepSeatedSealed()
            {
                Status = true,
                Priority = 0,
                Step = "蓝牙扫描测试",
                Command = "AT+SCANADD",
                PassFlag = "SCAN_OK",
                ErrorFlag = "NG",
                TimeoutMs = 9000,
                IsCombination = true,
                IsBluetoothBoard = true,
                BluethAccording = "-",
                AddtionAccording = "=",
                ValidValueRange = "0,88",
                ValueProcessingType = "蓝牙",
                AppendType = "蓝牙",
                AppendValue = "数据库"
            },
            ["写入蓝牙步骤"] = new TestItemDeepSeatedSealed()
            {
                Status = true,
                Priority = 0,
                Step = "蓝牙设置测试",
                Command = "prod AT+TEST=SET_MAC",
                PassFlag = "OK",
                ErrorFlag = "NG",
                IsCombination = true,
                BluethAccording = ":",
                AddtionAccording = ",",
                IsXorVerify = true,
                AppendType = "蓝牙",
                AppendValue = "随机(蓝牙)"
            },
            ["首次刷卡步骤"] = new TestItemDeepSeatedSealed()
            {
                Status = true,
                Priority = 0,
                Step = "第一次刷卡测试",
                Command = "prod AT+TEST=NFC_TEST",
                PassFlag = "OK",
                ErrorFlag = "NG",
                PassMatch = "(?-i)Card_ID\\W*((:?[^\\W]+\\s+){3}[^\\W]{2})",
                MaxRetryCount = 2,
                IsHandDownValue = true
            },
            ["验证刷卡步骤"] = new TestItemDeepSeatedSealed()
            {
                Status = true,
                Priority = 0,
                Step = "第二次刷卡测试",
                Command = "prod AT+TEST=NFC_TEST",
                PassFlag = "OK",
                ErrorFlag = "NG",
                PassMatch = "(?-i)Card_ID\\W*((:?[^\\W]+\\s+){3}[^\\W]{2})",
                IsLinkedToPrevious = true
            }
        };
    
    }

    public sealed class ActivitySectionModel
    {
        public ProductFlag CurrentProductFlag { set; get; } = ProductFlag.HYC;

        public string StalkerPreviousFlag { set; get; } = string.Empty;

        public ICollection<string> CusultColumnNames { set; get; } = [];

        public (string, string) ProductSelectedValuePair { set; get; } = new(); //  与viewmodel中的集合不同的是，当前收集非固定可用选项，viewmodel中的集合仅用于设置默认项

        public DemandType TestDemandType { set; get; } = DemandType.Invalid;

        public Dictionary<string, string> DBWorkOrderMap { set; get; } = [];

        public StringBuilder Device_TestRunningRecor { set; get; } = new(4096);

        public StringBuilder Tools_TestRunningRecor { set; get; } = new(4096);

        public Dictionary<string, KvpGroup> MesConfigMap { set; get; } = [];

        public int RegisterIsSecondaryKey { set; get; } = 0;

        public Action<double, string>? DimProcess { set; get; }

        public SemaphoreSlim AsyncLock { set; get; } = new(1, 1);

        public bool SemaphoreAbnormalStat { set; get; } = false;

        // product - process - isextend
        public ICollection<(string, string, bool)> EmbeddedIsExtend { set; get; } = [];

        public Dictionary<string, string> TableReserveDuty { get; } = new()
        {
            {
                "product_config_field", "CREATE TABLE IF NOT EXISTS product_config_field(" +
                                        "field_json TEXT NOT NULL COLLATE NOCASE," +
                                        "field_product TEXT NOT NULL COLLATE NOCASE," +
                                        "field_process TEXT NOT NULL COLLATE NOCASE)"
            },

            {
                "product_config_relation", "CREATE TABLE IF NOT EXISTS product_config_relation(" +
                                           "prd_id TEXT PRIMARY KEY," +
                                           "prd_name TEXT NOT NULL COLLATE NOCASE," +
                                           "prd_process TEXT NOT NULL COLLATE NOCASE," +
                                           "prd_treekey INTEGER NOT NULL CHECK (prd_apply IN (0, 1))," +
                                           "prd_apply INTEGER NOT NULL CHECK (prd_apply IN (0, 1)))"
            },

            {
                "workorder_preview", "CREATE TABLE workorder_preview (" +
                                     "workorder_num TEXT PRIMARY KEY, " +
                                     "product_name TEXT NULL, " +
                                     "product_type TEXT NULL, " +
                                     "sn_start TEXT NULL, " +
                                     "sn_end TEXT NULL, " +
                                     "imei_start TEXT NULL, " +
                                     "imei_end TEXT NULL, " +
                                     "version TEXT NULL)"
            },

            {
                "workorder_unfold", "CREATE TABLE workorder_unfold (" +
                                    "id TEXT PRIMARY KEY, " +
                                    "sn TEXT, " +
                                    "sn_suffix TEXT, " +
                                    "imei TEXT, " +
                                    "imei_suffix TEXT, " +
                                    "secret_key TEXT, " +
                                    "onenet_product_id TEXT, " +
                                    "onenet_register_id TEXT, " +
                                    "product_api_key TEXT, " +
                                    "device_api_key TEXT, " +
                                    "blue_mac TEXT, " +
                                    "state TEXT, " +
                                    "product_name TEXT, " +
                                    "product_type TEXT, " +
                                    "product_num TEXT, " +
                                    "product_version TEXT, " +
                                    "workorder_num TEXT, " +
                                    "ng TEXT, " +
                                    "ng1 TEXT, " +
                                    "using_time TEXT, " +
                                    "verify_time TEXT)"
            },

            {
                "dbfield_relation", "CREATE TABLE IF NOT EXISTS dbfield_relation(" +
                                    "prd_name TEXT NOT NULL COLLATE NOCASE," +
                                    "field_json TEXT NOT NULL COLLATE NOCASE," +
                                    "consult_columns TEXT NOT NULL COLLATE NOCASE)"
            },

            {
                "testresult_register", "CREATE TABLE IF NOT EXISTS testresult_register(" +
                                       "id INTEGER UNIQUE PRIMARY KEY AUTOINCREMENT," +
                                       "product TEXT NOT NULL COLLATE NOCASE," +
                                       "process TEXT NOT NULL COLLATE NOCASE," +
                                       "step TEXT NOT NULL COLLATE NOCASE," +
                                       "imei TEXT NOT NULL COLLATE NOCASE," +
                                       "origin TEXT NOT NULL COLLATE NOCASE," +
                                       "result INTEGER NOT NULL COLLATE NOCASE," +
                                       "subjoin TEXT NOT NULL COLLATE NOCASE," +
                                       "date TEXT NOT NULL COLLATE NOCASE)"
            }
        };

        public Dictionary<ProductFlag, List<StalkerStepTemplate.Template>> ProductStalkerMap = [];
    }

    /// <summary>
    /// <para>private bool _IsExtend</para>
    /// <para>private string TreeName</para>
    /// <para>private string TreeIcon</para>
    /// <para>private int TreeCount</para>
    /// <para>private bool IsChild</para>
    /// <para>private bool IsExpand</para>
    /// <para>private string TreeParent</para>
    /// </summary>
    public sealed class EmbeddedTreeStructure : Notify
    {
        public enum Identity
        {
            Nonaligned,
            Friendly,
            Unamiable,
            TreeNonaligned
        }

        private bool _IsExtend = true;

        public bool IsExpand
        {
            get => _IsExtend; set
            {
                _IsExtend = value;
                propertyChangeSend(nameof(IsExpand));
            }
        }

        public string TreeName { get; set; } = string.Empty;

        public string TreeIcon { get; set; } = Icon();

        public int TreeCount { get; set; } = 0;

        public bool IsChild { get; set; } = false;

        public string Date { get; set; } = string.Empty;

        public object? ExtraBindDing { get; set; } = null;

        public string TreeParent { get; set; } = string.Empty;

        public List<EmbeddedTreeStructure> ProductRelationChildTree { get; set; } = [];

        public static string Icon(bool isPrimary = true)
        {
            return isPrimary ? "\ue74a" : "\ue617";
        }
    }

    public sealed class TestStatiSticalTemplate : Notify
    {
        private string _TestProcess = string.Empty;

        public class InnerDatas : Notify
        {
            private string _TestStep = string.Empty;

            private int _TestPassCount = 0;

            private int _TestFailCount = 0;

            public string TestStep
            {
                set
                {
                    _TestStep = value;
                    propertyChangeSend(nameof(TestStep));
                }
                get
                {
                    return _TestStep;
                }
            }

            public int TestPassCount
            {
                set
                {
                    _TestPassCount = value;
                    propertyChangeSend(nameof(TestPassCount));
                }
                get
                {
                    return _TestPassCount;
                }
            }

            public int TestFailCount
            {
                set
                {
                    _TestFailCount = value;
                    propertyChangeSend(nameof(TestFailCount));
                }
                get
                {
                    return _TestFailCount;
                }
            }
        }

        public string TestProcess
        {
            set
            {
                _TestProcess = value;
                propertyChangeSend(nameof(TestProcess));
            }
            get
            {
                return _TestProcess;
            }
        }

        public ObservableCollection<InnerDatas> InnerSources { set; get; } = [];
    }

    public sealed class EmbeddedTreeStructureSelect
    {
        public string? TreeProduct { get; set; } = null;

        public string? TreeProcess { get; set; } = null;

        public string? TreeStep { get; set; } = null;

        public string? TreeHint { set; get; } = null;

        public void Clear()
        {
            TreeProduct = null;
            TreeProcess = null;
            TreeStep = null;
            TreeHint = null;
        }
    }

    public sealed class SupplementConfig : Notify
    {
        private string _Name = string.Empty;

        private string _Value = string.Empty;

        private bool _DelBorder = false;

        public string Name
        {
            set
            {
                _Name = value;
                propertyChangeSend(nameof(Name));
            }
            get
            {
                return _Name;
            }
        }

        public string Value
        {
            set
            {
                _Value = value;
                propertyChangeSend(nameof(Value));
            }
            get
            {
                return _Value;
            }
        }

        public bool DelBorder
        {
            set
            {
                _DelBorder = value;
                propertyChangeSend(nameof(DelBorder));
            }
            get
            {
                return _DelBorder;
            }
        }

        public string Step = string.Empty;
    }

    public sealed class DateTimePush : Notify
    {
        public string TimeFormat { get; } = "yyyy/M/dd";

        private string ProductName { set; get; } = string.Empty;

        private (string, string) Current { set; get; } = (string.Empty, string.Empty);

        private string _start;

        private string _end;

        private string _query;

        public DateTimePush()
        {
            string hoursDate = DateTime.Now.ToString(TimeFormat);
            _start = hoursDate;
            _end = hoursDate;
            _query = "查询";
        }

        public string Start
        {
            set
            {
                _start = value;
                propertyChangeSend(nameof(Start));
            }
            get
            {
                return _start;
            }
        }

        public string End
        {
            set
            {
                _end = value;
                propertyChangeSend(nameof(End));
            }
            get
            {
                return _end;
            }
        }

        public string Query
        {
            set
            {
                _query = value;
                propertyChangeSend(nameof(Query));
            }
            get
            {
                return _query;
            }
        }

        public ObservableCollection<string> Starts { set; get; } = [];

        public ObservableCollection<string> Ends { set; get; } = [];

        public void UpdateCurrent()
        {
            Current = (Start, End);
        }

        public bool CanUpdateData(string _product)
        {
            if (Current.Item1 != Start || Current.Item2 != End || ProductName != _product)
            {
                return true;
            }
            return false;
        }
    }

    public sealed class StalkerStepTemplate : Notify
    {
        public class Template : Notify
        {
            private string _Step = string.Empty;

            private bool _State = true;

            private string _Watch = "成功阈值";

            private string _Hint = string.Empty;

            private int _Date = 1;

            private string _WatchCount = "800";

            public ObservableCollection<ButtomFunc> ButActions { set; get; } =
            [
                new ButtomFunc
                {
                    BTName = "取消",
                    BTAction = "取消"
                },
                new ButtomFunc
                {
                    BTName = "确定",
                    BTAction = "清除记录"
                }
            ];

            public string Step
            {
                set
                {
                    _Step = value;
                    propertyChangeSend(nameof(Step));
                }
                get
                {
                    return _Step;
                }
            }

            public bool State
            {
                set
                {
                    _State = value;
                    propertyChangeSend(nameof(State));
                }
                get
                {
                    return _State;
                }
            }

            public string Watch
            {
                set
                {
                    _Watch = value;
                    propertyChangeSend(nameof(Watch));
                }
                get
                {
                    return _Watch;
                }
            }

            public string Hint
            {
                set
                {
                    _Hint = value;
                    propertyChangeSend(nameof(Hint));
                }
                get
                {
                    return _Hint;
                }
            }

            public int Date
            {
                set
                {
                    _Date = value;
                    propertyChangeSend(nameof(Date));
                }
                get
                {
                    return _Date;
                }
            }

            public string WatchCount
            {
                set
                {
                    _WatchCount = value;
                    propertyChangeSend(nameof(Watch));
                }
                get
                {
                    return _WatchCount;
                }
            }
        }

        public class ButtomFunc : Notify
        {
            private string _BTName = string.Empty;

            private string _BTAction = string.Empty;

            public string BTName
            {
                set
                {
                    _BTName = value;
                    propertyChangeSend(nameof(BTName));
                }
                get
                {
                    return _BTName;
                }
            }

            public string BTAction
            {
                set
                {
                    _BTAction = value;
                    propertyChangeSend(nameof(BTAction));
                }
                get
                {
                    return _BTAction;
                }
            }
        }

        private string _SelectFlag = "和易充";

        public string SelectFlag
        {
            set
            {
                _SelectFlag = value;
                propertyChangeSend(nameof(SelectFlag));
            }
            get
            {
                return _SelectFlag;
            }
        }

        public ObservableCollection<string> Steps { set; get; } = [];

        public ObservableCollection<bool> States { set; get; } = [true, false];

        public ObservableCollection<int> Dates { set; get; } = [1, 5, 10, 15, 20, 25, 30, 35, 40];

        public ObservableCollection<string> Watchs { set; get; } = ["成功阈值", "失败阈值", "成功阈值+抽样数量", "失败阈值+抽样数量"];

        public ObservableCollection<string> Buttoms { set; get; } = ["取消", "确定"];

        public ObservableCollection<string> Actions { set; get; } = ["取消", "清除记录"];

        public ObservableCollection<string> ProductFlags { set; get; } = [];

        public ObservableCollection<Template> Templates { set; get; } = [];

        public static ICollection<ProductFlag> ConvertFlag(string flag)
        {
            return ActivityAssistBehivor.Behivor.ProductFlagChzMap.GetSafetyKey(flag);
        }

        public void LoaderCommand(ProductFlag StepType)
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                Steps.Clear();
                foreach (var attribute in ActivityAssistBehivor.Behivor.AttributeExpectsMap)
                {
                    if (attribute.Key.Contains($"{StepType}") && attribute.Key.Contains("Step"))
                    {
                        foreach (var step in attribute.Value)
                        {
                            Steps.Add(step);
                        }
                        break;
                    }
                }
            });
        }

        public void LoderProductFlag()
        {
            Application.Current.Dispatcher.InvokeAsync(() =>
            {
                foreach (var flag in Enum.GetValues(typeof(ProductFlag)))
                {
                    if (flag is ProductFlag productFlag && 
                        ActivityAssistBehivor.Behivor.ProductFlagChzMap.TryGetValue(productFlag, out string? _Chz) &&
                        !ProductFlags.Contains(_Chz))
                    {
                        ProductFlags.Add(_Chz);
                    }
                }
            });
        }
    }

    public sealed class TopMenuOptions : Notify
    {
        private string _Icon = "\ue626";

        private string _MenuName = string.Empty;

        private ICommand _Command = new EasyCommand((param)=> { }, ()=>true);

        public string Icon
        {
            set
            {
                _Icon = value;
                propertyChangeSend(nameof(Icon));
            }
            get
            {
                return _Icon;
            }
        }

        public string MenuName
        {
            set
            {
                _MenuName = value;
                propertyChangeSend(nameof(MenuName));
            }
            get
            {
                return _MenuName;
            }
        }

        public ICommand Command
        {
            set
            {
                _Command = value;
                propertyChangeSend(nameof(Command));
            }
            get
            {
                return _Command;
            }
        }
    }

}
